# coding: utf-8

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from contextlib import contextmanager

db = {}


def init_db(app):
    global db

    db_config = app.config['DB']
    db_url = db_config.get('url')
    show_sql = db_config.get('show_sql')
    engine = create_engine(db_url, echo=show_sql)
    db['engine'] = engine

    Session = sessionmaker(bind=engine)
    db['Session'] = Session
    app.ctx['db'] = db


# 初始化一个sessison
def new_session():
    return db['Session']()


@contextmanager
def with_session():
    session = db['Session']()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()


# 初始化一个sessison
def session_begin():
    return db['Session'].begin()


# 初始化一个sessison
def engine():
    return db['engine']
